//
//  LoginViewController.m
//  DaiShengInvest
//
//  Created by davinci on 17/6/8.
//  Copyright © 2017年 davinci. All rights reserved.
//

#import "LoginViewController.h"
#import "FindPasswordViewController.h"
#import "TelNumberViewController.h"
#import "MessageVerifyViewController.h"
#import "AppDelegate.h"
#import "MainTabBarController.h"
#import "HomeViewController.h"

@interface LoginViewController ()<UITextFieldDelegate>

@property (nonatomic, weak)UIImageView * backImageView;

@property (nonatomic, weak)UIImageView * logeImage;

@property (nonatomic, weak)UITextField * accountText;

@property (nonatomic, weak)UITextField * passwordText;

@property (nonatomic, weak)UIButton * forgiveButton;

@property (nonatomic, weak)UIButton * loginButton;

@property (nonatomic, weak)UIButton * setupButton;

@property (nonatomic, weak)UIButton * moveToMainVCButton;

@property (nonatomic, weak)UILabel * showLabel;

@end

@implementation LoginViewController

//隐藏导航栏
-(void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = YES;
    
//    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
//    
//    NSString * userID = [userDefaults objectForKey:@"userId"];
//    
//    if (userID) {
//        
//        self.accountText.text = [userDefaults objectForKey:@"phone"];
//        self.passwordText.text = [userDefaults objectForKey:@"password"];
//    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"登录";
    
    [self setupUI];
    
//    [self loadData];
}


//页面搭建
- (void)setupUI{
    
    UIImageView * backImageView = [[UIImageView alloc] init];
    
    backImageView.backgroundColor = [UIColor whiteColor];
    backImageView.image = [UIImage imageNamed:@"背景"];
    
    self.backImageView = backImageView;
    
    [self.view addSubview:self.backImageView];
    
    
    UIImageView * logeImage = [[UIImageView alloc] init];
    
    logeImage.backgroundColor = [UIColor clearColor];
    logeImage.image = [UIImage imageNamed:@"d-club"];
    
    self.logeImage = logeImage;
    
    [self.backImageView addSubview:self.logeImage];
    
    
    UITextField * accountText = [[UITextField alloc] init];
    
    accountText.borderStyle = UITextBorderStyleLine;
    accountText.backgroundColor = [UIColor blackColor];
    //设置光标颜色
    accountText.tintColor = ColorWithRGB(0x808486);
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0x808486);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    accountText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"手机号" attributes:attrs];
    accountText.textColor = ColorWithRGB(0x808486);
    accountText.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22 * SCREENH6, 0)];
    //设置显示模式为永远显示(默认不显示)
    accountText.leftViewMode = UITextFieldViewModeAlways;
    accountText.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    UIView * rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 35 * SCREENH6, 26 * SCREENH6)];
    UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20 * SCREENH6, 26 * SCREENH6)];//WithImage:[UIImage imageNamed:@"手机号"]];
    image.image = [UIImage imageNamed:@"手机号"];
    [rightView addSubview:image];
    accountText.rightView = rightView;
    accountText.rightViewMode = UITextFieldViewModeAlways;
    accountText.keyboardType = UIKeyboardTypeNumberPad;
    accountText.keyboardAppearance = UIKeyboardAppearanceDark;
    
    self.accountText = accountText;
    
    [self.view addSubview:self.accountText];
    
    
    UITextField * passwordText = [[UITextField alloc] init];
    
    passwordText.borderStyle = UITextBorderStyleLine;
    passwordText.secureTextEntry = YES;
    passwordText.backgroundColor = [UIColor blackColor];
    passwordText.delegate = self;
    //设置光标颜色
    passwordText.tintColor = ColorWithRGB(0x808486);
    //修改占位符文字颜色
    NSMutableDictionary *attrs1 = [NSMutableDictionary dictionary];
    attrs1[NSForegroundColorAttributeName] = ColorWithRGB(0x808486);
    attrs1[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    passwordText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"密码" attributes:attrs1];
    passwordText.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    passwordText.textColor = ColorWithRGB(0x808486);
    passwordText.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22 * SCREENH6, 0)];
    //设置显示模式为永远显示(默认不显示)
    passwordText.leftViewMode = UITextFieldViewModeAlways;
    //    accountText.font = [UIFont systemFontOfSize:15];
    UIView * leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 35 * SCREENH6, 26 * SCREENH6)];
    UIImageView *image1=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20 * SCREENH6, 26 * SCREENH6)];//WithImage:[UIImage imageNamed:@"手机号"]];
    image1.image = [UIImage imageNamed:@"密码"];
    [leftView addSubview:image1];
    passwordText.rightView = leftView;
    passwordText.rightViewMode = UITextFieldViewModeAlways;
    passwordText.keyboardType = UIKeyboardTypeDefault;
    passwordText.keyboardAppearance = UIKeyboardAppearanceDark;

    
    self.passwordText = passwordText;
    
    [self.view addSubview:self.passwordText];
    
    
    UIButton * forgiveButton = [[UIButton alloc] init];
    
    [forgiveButton setTitle:@"找回密码?" forState:UIControlStateNormal];
    forgiveButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
//    forgiveButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [forgiveButton setTitleColor:ColorWithRGB(0xd3d3d3) forState:UIControlStateNormal];
    [forgiveButton addTarget:self action:@selector(FindPassword) forControlEvents:UIControlEventTouchUpInside];
    
    self.forgiveButton = forgiveButton;
    
    [self.view addSubview:self.forgiveButton];
    
    
    UIButton * loginButton = [[UIButton alloc] init];
    
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    loginButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18 * SCREENH6];//[UIFont systemFontOfSize:15];
//    [loginButton setBackgroundColor:ColorWithRGB(0xa92c44)];
    [loginButton setBackgroundImage:[UIImage imageNamed:@"注册"] forState:UIControlStateNormal];
    loginButton.layer.borderColor = [[UIColor blackColor] CGColor];
    //边框宽度
    loginButton.layer.borderWidth =1.0f;
    //处理圆角
    loginButton.layer.cornerRadius =5.0f;
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(didLoginButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.loginButton = loginButton;
    
    [self.view addSubview:self.loginButton];
    
    
    UIButton * setupButton = [[UIButton alloc] init];
    
    [setupButton setTitle:@"注册" forState:UIControlStateNormal];
    setupButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:17 * SCREENH6];
    [setupButton setBackgroundColor:[UIColor clearColor]];
    setupButton.layer.borderColor = [[UIColor grayColor] CGColor];
    //边框宽度
    setupButton.layer.borderWidth =1.0f;
    //处理圆角
    setupButton.layer.cornerRadius =5.0f;
    [setupButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [setupButton addTarget:self action:@selector(didSetupButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.setupButton = setupButton;
    
    [self.view addSubview:self.setupButton];
    
    
    UIButton * moveToMainVCButton = [[UIButton alloc] init];
    
    [moveToMainVCButton setTitle:@"随便逛逛" forState:UIControlStateNormal];
    moveToMainVCButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
//    [moveToMainVCButton setBackgroundColor:[UIColor lightGrayColor]];
    [moveToMainVCButton setTitleColor:ColorWithRGB(0x6c6c6c) forState:UIControlStateNormal];
    [moveToMainVCButton addTarget:self action:@selector(didmoveToMainVCButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.moveToMainVCButton = moveToMainVCButton;
    
    [self.view addSubview:self.moveToMainVCButton];
 
    
    UILabel * showLabel = [[UILabel alloc] init];
    
    showLabel.text = @"D-Club 交易俱乐部为DCM Group 戴盛集团交易品牌";
    showLabel.textColor = ColorWithRGB(0x6c6c6c);
    showLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:10 * SCREENH6];
    
    self.showLabel = showLabel;
    
    [self.view addSubview:self.showLabel];
}

//页面布局
- (void)viewDidLayoutSubviews{
    
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.mas_equalTo(self.view);
    }];
    
    [self.logeImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(40 * SCREENH6);
        make.width.mas_equalTo(229 * SCREENH6);
        make.height.mas_equalTo(154 * SCREENH6);
    }];
    
    
    [self.accountText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.logeImage.mas_bottom).offset(37 * SCREENH6);
        make.width.mas_equalTo(326 * SCREENH6);
        make.height.mas_equalTo(55 * SCREENH6);
    }];
    
    [self.passwordText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.accountText.mas_bottom).offset(13 * SCREENH6);
        make.width.mas_equalTo(326 * SCREENH6);
        make.height.mas_equalTo(55 * SCREENH6);//        make.width.height.mas_equalTo(self.accountText);
    }];
    
    [self.forgiveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.passwordText.mas_trailing);
        make.top.mas_equalTo(self.passwordText.mas_bottom).offset(18 * SCREENH6);
//        make.width.mas_equalTo(50 * SCREENH6);
//        make.height.mas_equalTo(20 * SCREENH6);
    }];
    
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.passwordText);
        make.top.mas_equalTo(self.passwordText.mas_bottom).offset(52 * SCREENH6);
        make.height.mas_equalTo(63 * SCREENH6);
    }];
    
    
    [self.setupButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.loginButton);
        make.top.mas_equalTo(self.loginButton.mas_bottom).offset(20 * SCREENH6);
        make.height.mas_equalTo(63 * SCREENH6);
    }];
    
    
    [self.moveToMainVCButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.setupButton.mas_bottom).offset(37.5 * SCREENH6);
//        make.height.mas_equalTo(25 * SCREENH6);
    }];
    
    [self.showLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.moveToMainVCButton.mas_bottom).offset(20 * SCREENH6);
        //        make.height.mas_equalTo(25 * SCREENH6);
    }];
}


//忘记密码
- (void)FindPassword{
    
    FindPasswordViewController * findpasswordVC = [FindPasswordViewController new];
    
    
    [self.navigationController pushViewController:findpasswordVC animated:YES];
}

//点击登录按钮
- (void)didLoginButton{
    
//    向后台发送用户输入的账号密码
    
    [self.passwordText resignFirstResponder];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
//    NSDictionary *dictionary = [userDefaults dictionaryRepresentation];
//    
//    for(NSString *key in [dictionary allKeys]){
//        
//        [userDefaults removeObjectForKey:key];
//        [userDefaults synchronize];
//    }
    
    if ([self.accountText.text isEqualToString:@""] || [self.passwordText.text isEqualToString:@""]) {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"请填写登录信息！"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  //响应事件
                                                                  //                                                                  NSLog(@"action = %@", action);
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else{
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        NSDictionary * parametersDic = @{@"phone":self.accountText.text,@"password":self.passwordText.text};
        
        [[NetworkTool sharedTools] POST:@"site/login" parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            
            NSString * codeString = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
            
            if ([codeString isEqualToString:@"0"]) {
                
                NSDictionary * paramDict = responseObject[@"param"];
                
                NSString * createTimeStr = paramDict[@"createTime"];
                NSString * lastLoginTimeStr = paramDict[@"lastLoginTime"];
                NSString * userIdStr = paramDict[@"userId"];
                
                
                [userDefaults setObject:createTimeStr forKey:@"createTime"];
                [userDefaults setObject:lastLoginTimeStr forKey:@"lastLoginTime"];
                [userDefaults setObject:userIdStr forKey:@"userId"];
                [userDefaults setObject:self.accountText.text forKey:@"phone"];
                [userDefaults setObject:self.passwordText.text forKey:@"password"];
                
                [userDefaults synchronize];
                
                AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                
                MainTabBarController *tabs = [[MainTabBarController alloc] init];
                
                appDelegate.window.rootViewController = tabs;
                
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseObject[@"msg"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
//                                                                          NSLog(@"action = %@", action);
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
                
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
//            NSLog(@"%@",error);
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"服务器内部错误！"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
//                                                                      NSLog(@"action = %@", action);
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }];

    }
    
   

}

//点击注册按钮
- (void)didSetupButton{
    
    MessageVerifyViewController * telVC = [MessageVerifyViewController new];
    
    telVC.fromString = @"LoginString";
    
    [self.navigationController pushViewController:telVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)didmoveToMainVCButton{
    
    //切换根视图控制器
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    MainTabBarController *tabs = [[MainTabBarController alloc] init];
    
//    tabs.homeVC.noLogin = @"no";
    
//    if(tabs.selectedIndex == 0){
//        
//        HomeViewController * vc = [HomeViewController new];
//    }
    
    appDelegate.window.rootViewController = tabs;
    
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.passwordText resignFirstResponder];
    
    return YES;
}






- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.passwordText resignFirstResponder];
    
    [self.accountText resignFirstResponder];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
